package com.stress.testing.agent.resolver;

import com.stress.testing.agent.Logger;
import com.stress.testing.common.AgentContext;
import com.stress.testing.common.AgentExtendJarClassLoader;
import com.stress.testing.common.ClassFileTransformerRegistry;

public class DefaultClassFileTransformerRegistryResolver implements ClassFileTransformerRegistryResolver {
    private static Logger logger = Logger.getLogger(DefaultClassFileTransformerRegistryResolver.class);

    @Override
    public ClassFileTransformerRegistry resolve(AgentContext context) {
        AgentExtendJarClassLoader extendJarClassLoader = null;

        if (!(context.getAgentExtendJarClassLoader() instanceof AgentExtendJarClassLoader)) {
            throw new RuntimeException("无法转换为类型AgentExtendJarClassLoader的实例");
        }

        extendJarClassLoader = (AgentExtendJarClassLoader) context.getAgentExtendJarClassLoader();

        Class<?> clazz = null;
        try {
            clazz = extendJarClassLoader.loadClass(context.getClassFileTransformerRegistryClass());
            return ClassFileTransformerRegistry.class.cast(clazz.newInstance());
        } catch (Exception e) {
            logger.error("创建ClassFileTransformerRegistry失败", e);
            throw new RuntimeException("创建ClassFileTransformerRegistry失败");
        }
    }
}
